package com.sishu.service.impl;

import com.sishu.mapper.*;
import com.sishu.pojo.Options;
import com.sishu.pojo.Questionlibrary;
import com.sishu.pojo.Transactionrecord;
import com.sishu.pojo.dto.Questionlibrarydto;
import com.sishu.service.QuestionlibraryService;
import com.sishu.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

@Slf4j
@Service
public class QuestionlibraryServiceimpl implements QuestionlibraryService {

    @Resource
    private QuestionlibraryMapper questionlibraryMapper;

    private Set<Integer> usedQuestionIds = Collections.synchronizedSet(new HashSet<>());


    @Resource
    private LocationrecordMapper locationrecordMapper;

    @Resource
    private OptionsMapper optionsMapper;

    @Resource
    private GusMapper gusMapper;

    @Resource
    private AssetMapper assetMapper;

    @Resource
    private TransactionrecordMapper transactionrecordMapper;
    ;

    @Override
    public Result getrandomquestion(String classification) {
        if (classification == null || classification.isEmpty()) {
            return new Result<>(500, "参数错误", false);
        }

//        List<Questionlibrary> allTikus = questionlibraryMapper.selcetAll();//查询数据库中所有的题目放到一个list中
        List<Questionlibrary> allTikus = questionlibraryMapper.selcetbyclassification(classification);

        System.out.println("allTikus=" + allTikus);
        if (CollectionUtils.isEmpty(allTikus)) {//如果数据库中没有数据那么会返回题库为空
            return new Result<>(500, "题库为空", false);
        }

        List<Questionlibrary> availableTikus = new ArrayList<>();//存储未被使用过的题目
        for (Questionlibrary tiku : allTikus) {
            if (!usedQuestionIds.contains(tiku.getQuestionId())) {//遍历 allTikus 列表，检查每个题目的 questionId 是否在 usedQuestionIds 集合中
                availableTikus.add(tiku);//如果 questionId 不在 usedQuestionIds 中，将该题目添加到 availableTikus 列表中
            }
        }

        if (availableTikus.isEmpty()) {
            // 所有题目都已使用过，清空已使用的集合
            usedQuestionIds.clear();
            availableTikus.addAll(allTikus);
        }

        // 随机选择一个题目
        int randomIndex = ThreadLocalRandom.current().nextInt(availableTikus.size());
        Questionlibrary selectedTiku = availableTikus.get(randomIndex);

        List<Options> options = optionsMapper.selectOptionsByQuestionId(selectedTiku.getQuestionId());
        selectedTiku.setOptions(options);


        // 记录已使用的 questionId
        usedQuestionIds.add(selectedTiku.getQuestionId());

        return new Result<>(200, "data", "随机题目获取成功", selectedTiku, true);
    }

    @Override
    public Result answerrandomquestion(Integer questionId, String answer) {
        // 根据题目ID查询题目  如果后续加困难度的话,需要在后面加一个参数
        Questionlibrary selectbyquestionid = questionlibraryMapper.selectbyquestionid(questionId);
        if (selectbyquestionid == null) {
            return new Result(500, "题目不存在", false);
        } else {
            if (selectbyquestionid.getAnswer().equals(answer)) {
                return new Result(202, "答案正确", true);
            } else {
                return new Result(202, "答案错误", false);
            }
        }
    }


    /**
     * @author linyi
     * @date 2025-02-09 09:29:16
     * @description 随机获取一道当前课时的题库中的题目
     */

    @Override
    public Result getrandomquestionbyclasshour(Integer classHour, String classification) {

        if (classHour == null) {  //如果传过来的classHour为空,那么就直接返回随机获取一道题
            return getrandomquestion(classification);
        }

        if (classification == null || classification.isEmpty()) {
            return new Result<>(500, "参数错误", false);
        }

        List<Questionlibrary> allTikus = questionlibraryMapper.selcetbyclassificationbyclasshour(classHour, classification);
        System.out.println("allTikus=" + allTikus);

        if (CollectionUtils.isEmpty(allTikus)) {//如果数据库中没有数据那么会返回题库为空
            return new Result<>(500, "题库为空", false);
        }

        List<Questionlibrary> availableTikus = new ArrayList<>();//存储未被使用过的题目
        for (Questionlibrary tiku : allTikus) {
            if (!usedQuestionIds.contains(tiku.getQuestionId())) {//遍历 allTikus 列表，检查每个题目的 questionId 是否在 usedQuestionIds 集合中
                availableTikus.add(tiku);//如果 questionId 不在 usedQuestionIds 中，将该题目添加到 availableTikus 列表中
            }
        }

        if (availableTikus.isEmpty()) {
            // 所有题目都已使用过，清空已使用的集合
            usedQuestionIds.clear();
            availableTikus.addAll(allTikus);
        }

        // 随机选择一个题目
        int randomIndex = ThreadLocalRandom.current().nextInt(availableTikus.size());
        Questionlibrary selectedTiku = availableTikus.get(randomIndex);

        List<Options> options = optionsMapper.selectOptionsByQuestionId(selectedTiku.getQuestionId());
        selectedTiku.setOptions(options);


        // 记录已使用的 questionId
        usedQuestionIds.add(selectedTiku.getQuestionId());

        return new Result<>(200, "data", "随机题目获取成功", selectedTiku, true);
    }

    @Override
    public Result insertquestion(List<Questionlibrary> questionlibrary) {

        for (Questionlibrary questionlibrary1 : questionlibrary) {

            //插入题目
            questionlibraryMapper.insert(questionlibrary1);

            //得到选项
            List<Options> options = questionlibrary1.getOptions();
            log.info("options=" + options);

            for (Options option : options) {
                //将选项questionId设置为题目主键回填的questionId
                option.setQuestionId(questionlibrary1.getQuestionId());
                optionsMapper.insert(option);
            }

        }
        return new Result<>(202, "插入成功", true);
    }

    @Override
    public Result answerrevivequestion(List<Questionlibrarydto> answers) { //传过来的答案为answer.getAnswer()
        int count = 0;  //回答正确的数量
        for (Questionlibrarydto answer : answers) {
            //数据库种的答案为questionlibraryMapper.selectbyquestionid(answer.getQuestionId()).getAnswer()
            //如果答案相同的情况下数量增加最多到3
            if (answer.getAnswer().equals(questionlibraryMapper.selectbyquestionid(answer.getQuestionId()).getAnswer())) {

                count++;
            }
        }

        //获得partyA和groupId
        String partyA = answers.get(0).getPartyA();  // partyA就是学生学号
        String groupId = answers.get(0).getGroupId(); // groupId就是小组号

        //回答正确1次的情况下
        if (count == 1) {
            //设置该用户复活成功
            int money = 1000;
            assetMapper.reviveasset(partyA, groupId, money);

            //创建交易记录表
            Transactionrecord transactionrecord = new Transactionrecord();
            transactionrecord.setPartyA(partyA);
            transactionrecord.setMoneyA(money);
            transactionrecord.setPartyB("bank");
            transactionrecord.setMoneyB(-money);
            transactionrecord.setType("1");
            transactionrecord.setGroupId(groupId);
            transactionrecord.setTypeDescribe("注资");
            transactionrecord.setCreateTime(LocalDateTime.now());
            transactionrecordMapper.insert(transactionrecord);
            return new Result(202, "注资成功", true);
        }
        //回答正确2次的情况下
        else if (count == 2) {
            int money = 2000;
            assetMapper.reviveasset(partyA, groupId, money);

            //创建交易记录表
            Transactionrecord transactionrecord = new Transactionrecord();
            transactionrecord.setPartyA(partyA);
            transactionrecord.setMoneyA(money);
            transactionrecord.setPartyB("bank");
            transactionrecord.setMoneyB(-money);
            transactionrecord.setType("1");
            transactionrecord.setGroupId(groupId);
            transactionrecord.setTypeDescribe("注资");
            transactionrecord.setCreateTime(LocalDateTime.now());
            transactionrecordMapper.insert(transactionrecord);
            return new Result(202, "注资成功", true);
        }
        //回答正确3次的情况下
        else if (count == 3) {
            int money = 3000;
            assetMapper.reviveasset(partyA, groupId, money);

            //创建交易记录表
            Transactionrecord transactionrecord = new Transactionrecord();
            transactionrecord.setPartyA(partyA);
            transactionrecord.setMoneyA(money);
            transactionrecord.setPartyB("bank");
            transactionrecord.setMoneyB(-money);
            transactionrecord.setType("1");
            transactionrecord.setGroupId(groupId);
            transactionrecord.setTypeDescribe("注资");
            transactionrecord.setCreateTime(LocalDateTime.now());
            transactionrecordMapper.insert(transactionrecord);
            return new Result(202, "注资成功", true);
        }
        //回答全错的情况下
        else {
            gusMapper.setisdeleteone(partyA, groupId); //设置该用户破产
            locationrecordMapper.deleteallground(partyA, groupId);  //删除该用户所有的地盘
            return new Result(202, "已破产", false);
        }
    }

}
